package co.edu.poli.ficb.agl.automatable.gui;

import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.Collection;

import co.edu.poli.ficb.agl.automatable.modelo.automatas.Estado;
import co.edu.poli.ficb.agl.automatable.modelo.automatas.Transicion;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.Context;
import edu.uci.ics.jung.graph.util.Pair;
import edu.uci.ics.jung.visualization.decorators.EdgeShape;
import edu.uci.ics.jung.visualization.decorators.EdgeShape.Loop;

/**
 * 
 * @author Diego Satoba
 * 
 */
public class PAQuadCurve extends EdgeShape.QuadCurve<Estado, Transicion> {
	
	/**
	 * a convenience instance for other edge shapes to use for self-loop edges
	 * where parallel instances will not overlay each other.
	 */
	@SuppressWarnings("rawtypes")
	protected static Loop loop = new Loop();
	
	/**
	 * Singleton instance of the Line2D edge shape
	 */
	private static Line2D line = new Line2D.Float(0.0f, 0.0f, 1.0f, 0.0f);
	
	public PAQuadCurve() {
	}

	@Override
	public Shape transform(Context<Graph<Estado, Transicion>, Transicion> context) {

		Graph<Estado, Transicion> grafo = context.graph;

		Transicion regla = context.element;

		Pair<Estado> endpoints = grafo.getEndpoints(regla);

		Collection<Transicion> reglas = new ArrayList<Transicion>();
		
		// TODO revisar esto.
		Estado estadoFuente = null;
		Estado estadoDestino = null;
		for (Estado e : grafo.getVertices()) {
			if (e.equals(regla.getEstadoFuente())) {
				estadoFuente = e;
			} else if (e.equals(regla.getEstadoDestino())) {
				estadoDestino = e;
			}
		}

		reglas.addAll(grafo.findEdgeSet(estadoFuente, estadoDestino));

		reglas.addAll(grafo.findEdgeSet(estadoDestino, estadoFuente));

		if (endpoints != null) {
			boolean isLoop = endpoints.getFirst().equals(endpoints.getSecond());
			if (isLoop) {
				// return loop.transform(context);
				return super.transform(context);
			}
		}

		if (reglas.size() == 1)
			return line;
		else
			return super.transform(context);
	}
}
